import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

let request = axios.create({
    baseURL: '/api',
    timeout: 5000,
})

request.interceptors.request.use(config => {
    const useStore = useUserStore()
    config.headers.token = useStore.token
    return config
})

request.interceptors.response.use(
    response => {
        return response.data
    },
    error => {
        let message = ''
        let status = error.response.status

        switch (status) {
            case 404:
                message = '请求地址不存在'
                break
            case 500:
                message = '服务器繁忙'
                break
            case 401:
                message = 'Token 过期'
                break
            case 403:
                message = '没有权限访问'
                break
        }

        ElMessage({
            type: 'error',
            message,
        })

        return Promise.reject(error)
    },
)

export default request
